import axios from 'axios'
import { baseURL } from '@/config/net.config.js'
import store from '@/store'
//获取当前日期
export function getNowDate() {
  let date = new Date()
  let y1 = date.getFullYear()
  let MM1 = date.getMonth() + 1
  MM1 = MM1 < 10 ? '0' + MM1 : MM1
  let d1 = date.getDate()
  d1 = d1 < 10 ? '0' + d1 : d1
  return y1 + '-' + MM1 + '-' + d1
}

//请求excel接口
export async function exportExcelRequest(url, params) {
  return axios({
    url: baseURL + url,
    method: 'get',
    responseType: 'blob',
    params,
  })
}
//导出excel
export function exportExcel(url, params, fileName = '未命名.xls') {
  exportExcelRequest(url, params).then((res) => {
    let blob = new Blob([res.data]) //res为从后台返回的数据
    if ('msSaveOrOpenBlob' in navigator) {
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }
  })
}
// 生成随机数
export function getRandomNum(minNum, maxNum) {
  return Math.floor(Math.random() * (maxNum - minNum) + minNum)
}

const token = store.getters['user/accessToken']
const config = {
  headers: {
    Authorization: `Bearer ${token}`,
  },
}

// 上传文件
//fileType：文件类型
export async function uploadImage(file, fileType, apiUrl) {
  var imageUrl = ''
  //上传文件单片2MB
  var chunkSize = 1024 * 1024 * 2
  // 总分片数量
  var chunks = Math.ceil(file.size / chunkSize)
  var requestId = ''
  // 分包上传文件
  for (let index = 0; index < chunks; index++) {
    var tempFile = null
    // 最后一包
    if (index === chunks - 1) {
      tempFile = file.slice(index * chunkSize)
    } else {
      tempFile = file.slice(index * chunkSize, (index + 1) * chunkSize)
    }

    // 封装请求参数
    var data = new FormData()
    data.append('file', tempFile)
    data.append('requestId', requestId)
    data.append('total', chunks)
    data.append('index', index)
    data.append('fileName', file.name)
    data.append('fileType', fileType)
    var res = await axios.post(baseURL + apiUrl, data, config)
    if (res.data.code === 200) {
      if (index === chunks - 1) {
        // 最后一包上传成功获取图片地址
        imageUrl = res.data.data.url
      }
      // 获取请求id
      requestId = res.data.data.requestId
    }
  }
  return imageUrl
}
